package cn.iocoder.an.module.business.service.faultclassification;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.an.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.an.module.business.controller.admin.equipmentmanage.vo.ImportRespVO;
import cn.iocoder.an.module.business.controller.admin.maintenanceclassification.vo.MaintenanceClassificationSaveReqVO;
import cn.iocoder.an.module.business.dal.dataobject.maintenanceclassification.MaintenanceClassificationDO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.micrometer.common.util.StringUtils;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import cn.iocoder.an.module.business.controller.admin.faultclassification.vo.*;
import cn.iocoder.an.module.business.dal.dataobject.faultclassification.FaultClassificationDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.pojo.PageParam;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import cn.iocoder.an.module.business.dal.mysql.faultclassification.FaultClassificationMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.an.module.business.enums.ErrorCodeConstants.*;

/**
 * 故障类型 Service 实现类
 *
 * @author zzy
 */
@Service
@Validated
public class FaultClassificationServiceImpl implements FaultClassificationService {

    @Resource
    private FaultClassificationMapper faultClassificationMapper;

    @Override
    public Long createFaultClassification(FaultClassificationSaveReqVO createReqVO) {
        // 插入
        checkRepeatName(createReqVO);
        FaultClassificationDO faultClassification = BeanUtils.toBean(createReqVO, FaultClassificationDO.class);
        faultClassificationMapper.insert(faultClassification);

        // 返回
        return faultClassification.getId();
    }

    @Override
    public void updateFaultClassification(FaultClassificationSaveReqVO updateReqVO) {
        // 校验存在
        validateFaultClassificationExists(updateReqVO.getId());
        checkRepeatName(updateReqVO);
        // 更新
        FaultClassificationDO updateObj = BeanUtils.toBean(updateReqVO, FaultClassificationDO.class);
        faultClassificationMapper.updateById(updateObj);
    }

    @Override
    public void deleteFaultClassification(Long id) {
        // 校验存在
        validateFaultClassificationExists(id);
        // 删除
        faultClassificationMapper.deleteById(id);
    }

    @Override
        public void deleteFaultClassificationListByIds(List<Long> ids) {
        // 删除
        faultClassificationMapper.deleteByIds(ids);
        }


    private void validateFaultClassificationExists(Long id) {
        if (faultClassificationMapper.selectById(id) == null) {
            throw exception(FAULT_CLASSIFICATION_NOT_EXISTS);
        }
    }

    @Override
    public FaultClassificationDO getFaultClassification(Long id) {
        return faultClassificationMapper.selectById(id);
    }

    @Override
    public PageResult<FaultClassificationDO> getFaultClassificationPage(FaultClassificationPageReqVO pageReqVO) {
        return faultClassificationMapper.selectPage(pageReqVO);
    }

    @Override
    public ImportRespVO importExcelData(List<FaultClassificationImportExcelVO> list, boolean isUpdateSupport) {
        // 1.1 参数校验
        if (CollUtil.isEmpty(list)) {
            throw exception(IMPORT_EQUIPMENT_MANAGE_NOT_EXISTS);
        }

        //2.记录成功或失败记录
        ImportRespVO respVO = ImportRespVO.builder().insertNameList(new ArrayList<>())
                .updateNameList(new ArrayList<>()).failureMap(new LinkedHashMap<>()).build();

        AtomicInteger count = new AtomicInteger(1);
        list.forEach(item -> {
            count.incrementAndGet();//记录行号

            // 2.1.1 校验维修分类名称
            if (StringUtils.isEmpty(item.getName())) {
                respVO.getFailureMap().put("第" + count + "行数据", "维修分类名称不能为空!");
                return;
            }

            // 2.1.2 校验状态
            if (item.getStatus() == null) {
                respVO.getFailureMap().put("第" + count + "行数据", "状态不能为空");
                return;
            }

            String name = item.getName();
            LambdaQueryWrapper<MaintenanceClassificationDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MaintenanceClassificationDO::getName, name);
            FaultClassificationDO exists = faultClassificationMapper.selectFirstOne(
                    FaultClassificationDO::getName, name
            );
            // 2.1.3 如果存在相同名称的维修分类  判断是否允许更新
            if (exists != null) {
                if (isUpdateSupport) {
                    //允许更新 先查询出
                    //设置ID
                    item.setId(exists.getId());
                    faultClassificationMapper.updateById(BeanUtils.toBean(item, FaultClassificationDO.class));
                    respVO.getUpdateNameList().add(item.getName());
                }else {
                    respVO.getFailureMap().put(item.getName(),MAINTENANCE_CLASSIFICATION_EXISTS.getMsg());
                }
            } else {
                //不存在
                faultClassificationMapper.insert(BeanUtils.toBean(item, FaultClassificationDO.class));
                respVO.getInsertNameList().add(item.getName());
            }
        });
        return respVO;
    }

    @Override
    public List<FaultClassificationDO> getAllList() {
        //查询启用状态的
        LambdaQueryWrapper<FaultClassificationDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FaultClassificationDO::getStatus, 1);
        return faultClassificationMapper.selectList(queryWrapper);
    }

    public void checkRepeatName(FaultClassificationSaveReqVO saveReqVO) {
        LambdaQueryWrapperX<FaultClassificationDO> queryWrapper = new LambdaQueryWrapperX<>();
        String name = saveReqVO.getName();
        queryWrapper.eq(FaultClassificationDO::getName, name);
        if (saveReqVO.getId() == null) {
            //1.新增  检查是否已经存在相同名称的分类
            if (faultClassificationMapper.exists(queryWrapper)) {
                throw exception(FAULT_CLASSIFICATION_ALREADY_EXISTS);
            }
        } else {
            //2.如果是修改操作 排除自身
            queryWrapper.ne(FaultClassificationDO::getId, saveReqVO.getId());
            if (faultClassificationMapper.exists(queryWrapper)) {
                throw exception(FAULT_CLASSIFICATION_ALREADY_EXISTS);
            }
        }
    }

}